package com.soft.javase.day11.copy;

import java.io.*;

/**
 * @author yzg
 * @desc TODO
 * @date 2025/5/9
 */
public class DirectoryCopy {
    public static void copyDirectory(String srcDir, String destDir) throws IOException {
        File src = new File(srcDir);
        File dest = new File(destDir);

        if (!dest.exists()) {
            dest.mkdirs();
        }

        File[] files = src.listFiles();
        if (files != null) {
            for (File file : files) {
                String destPath = dest.getAbsolutePath() + File.separator + file.getName();
                if (file.isDirectory()) {
                    copyDirectory(file.getAbsolutePath(), destPath);
                } else {
                    copyFile(file.getAbsolutePath(), destPath);
                }
            }
        }
        System.out.println("文件夹拷贝完成: " + destDir);
    }

    private static void copyFile(String srcPath, String destPath) {
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath))) {

            byte[] buffer = new byte[8192];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String srcDir = "sourceDir";
        String destDir = "destDir";

        try {
            copyDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
